﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;

namespace FinApp.Utils.VisualTree {
    /// <summary>
    /// Couple of simple helpers for walking the visual tree
    /// </summary>
    public static class VisualTreeExtensions {

        /// <summary>
        /// Gets the ancestors of the element, up to the root
        /// </summary>
        /// <param name="node">The element to start from</param>
        /// <returns>An enumerator of the ancestors</returns>
        public static IEnumerable<FrameworkElement> GetVisualAncestors(this FrameworkElement node) {
            FrameworkElement parent = node.GetVisualParent();
            while (parent != null) {
                yield return parent;
                parent = parent.GetVisualParent();
            }
        }

        /// <summary>
        /// Gets the visual parent of the element
        /// </summary>
        /// <param name="node">The element to check</param>
        /// <returns>The visual parent</returns>
        public static FrameworkElement GetVisualParent(this FrameworkElement node) {
            return VisualTreeHelper.GetParent(node) as FrameworkElement;
        }

        /// <summary>
        /// Finds object in control's template by it's name.
        /// </summary>
        /// <param name="templatedParent">Templated parent.</param>
        /// <param name="name">Objects name.</param>
        /// <returns>Object reference if found, null otherwise.</returns>
        public static object TemplateFindName(this FrameworkElement templatedParent, string name) {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(templatedParent); i++) {
                DependencyObject child = VisualTreeHelper.GetChild(templatedParent, i);
                if (child is FrameworkElement) {
                    if (((FrameworkElement)child).Name == name) {
                        return child;
                    } else {
                        object subChild = ((FrameworkElement)child).TemplateFindName(name);
                        if (subChild != null && subChild is FrameworkElement && ((FrameworkElement)subChild).Name == name) {
                            return subChild;
                        }
                    }
                }
            }
            return null;
        }
    }
}
